package com.mew.auc.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mew.auc.config.GoldConfig;
import com.mew.auc.rest.GoogleAccessTokenResponse;
import com.mew.common.entity.record.RechargeRecord;
import com.mew.common.rest.user.BuyRequestMessage;
import com.mew.common.util.HttpUtils;
import com.mew.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Slf4j
@Component
public class GooglePlayUtils {

    @Autowired
    private GoldConfig goldConfig;

    public RechargeRecord getGoogleProductResponse(BuyRequestMessage buyRequestMessage) {

        String access_token = getGoogleAccessTokenResponse().getAccess_token();

        RechargeRecord productResponse = null;
        try {
            productResponse = getRechargeRecord(buyRequestMessage, productResponse,access_token);
        } catch (Exception e) {
            //报错了重来
            access_token = getGoogleAccessTokenResponse().getAccess_token();
            productResponse = getRechargeRecord(buyRequestMessage, productResponse,access_token);
        }

        if (null == productResponse || StringUtils.isEmpty(productResponse.getOrderId())) {
            //没有也重来
            access_token = getGoogleAccessTokenResponse().getAccess_token();
            productResponse = getRechargeRecord(buyRequestMessage, productResponse,access_token);
        }


        return productResponse;
    }

    /**
     * 获取购买的商品信息
     * @param buyRequestMessage
     * @param productResponse
     * @param access_token
     * @return
     */
    @Nullable
    private RechargeRecord getRechargeRecord(BuyRequestMessage buyRequestMessage, RechargeRecord productResponse,String access_token) {
        String yz = "https://www.googleapis.com/androidpublisher/v3/applications/" + buyRequestMessage.getPackageName() + "/purchases/products/" + buyRequestMessage.getProductId() + "/tokens/" + buyRequestMessage.getPurchaseToken() + "?access_token=" + access_token;
        System.out.println(yz);
        String s = HttpUtils.get(yz);
        productResponse = JSON.parseObject(s, RechargeRecord.class);
        return productResponse;
    }
    /**
     * 获得返回的refresh_token，妥善保存此token。以后的请求中都不会再出现，对于当前创建的账号的唯一且永久有效的。
     *
     * 这一步调用不成功的，注意返回的code码里如果有%2F记得换成/。
     *
     * 简单来说前面的都是权限校验，准备工作，我们主要是为了获取access_token。然后来调用谷歌的商品校验接口
     * @return
     */
    private GoogleAccessTokenResponse getGoogleAccessTokenResponse() {
        try {
            String grant_type = "refresh_token";//固定
//            String client_id = "744081267536-taebi1flssa7mvsd6dkp8ri89iva41aq.apps.googleusercontent.com";
//            String client_secret = "shtEj7UdoulZWvigmiDM8J2r";
//            String refresh_token = "1//0eBb0SoDM8I93CgYIARAAGA4SNwF-L9IrQdOmwwQHSiaS1XZaykpLx6LZJt5ygCQ9jB7_jqQ2av0ZSJ7xP_ZQQlA1g06GaR4zIZ8";

            String client_id = goldConfig.getClient_id();
            String client_secret = goldConfig.getClient_secret();
            String refresh_token = goldConfig.getRefresh_token();

            HashMap<String, String> map = new HashMap<>();
            map.put("grant_type", grant_type);
            map.put("client_id", client_id);
            map.put("client_secret", client_secret);
            map.put("refresh_token", refresh_token);


            String url = "https://accounts.google.com/o/oauth2/token";

//            System.setProperty("http.proxySet", "true");
//            System.setProperty("http.proxyHost", "127.0.0.1");
//            System.setProperty("http.proxyPort", "" + 1081);
//
//            // 针对https也开启代理
//            System.setProperty("https.proxyHost", "127.0.0.1");
//            System.setProperty("https.proxyPort", "" + 1081);

            JSONObject jsonObject = HttpUtils.okhttpPost(url, JSON.parseObject(JSON.toJSONString(map)));

            GoogleAccessTokenResponse response = jsonObject.toJavaObject(GoogleAccessTokenResponse.class);
            return response;
        } catch (Exception e) {
            log.error("充值 获取access_token失败,{}",e);
            return null;
        }
    }


    public static void main(String[] args) {
        String j = "{\"productId\":\"oscar_30\",\"packageName\":\"com.oscar.ec\",\"uid\":48,\"purchaseToken\":\"dipbdipcbneialelodllhhal.AO-J1Owelz7fqT3soRGLMAcwqU8eUQz2bJyFLr1hiCmFibG0JAt1Ieq-dYs1M0ak9khEFdtrGe3B5owqe6exZYfxboSr_t1hwQ\"}";
        BuyRequestMessage response = JSON.parseObject(j, BuyRequestMessage.class);
        RechargeRecord googleProductResponse = new GooglePlayUtils().getGoogleProductResponse(response);
        System.out.println(googleProductResponse);
    }


}
